﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Repository.Transaction;
using Icoders.MarketTracker.Core.Transaction;
using Icoders.MarketTracker.Web.Lib.Model;
using Icoders.MarketTracker.Web.Lib.Security;
using Icoders.MarketTracker.Web.Lib.Services;
using Icoders.MarketTracker.Web.Lib.Util;
using Icoders.MarketTracker.Web.Lib.Validation;

namespace Icoders.MarketTracker.Web.Areas.Mobile.Controllers
{
    [CustomAuthorize(Roles = "ROLE_FSRUSER")]
    public class OrderController : Controller
    {
        private IPointOfPurchaseRepository _pointOfPurchaseRepository;
        private IClientRepository _clientRepository;
        public IDropDownService _dropDownService;
        private IProductRepository _productRepository;
        private IPurchaseOrderRepository _purchaseOrderRepository;
        private IUserRepository _userRepository;
        private IAuditTrailRepository _auditTrailRepository;

        public OrderController(IPointOfPurchaseRepository pointOfPurchaseRepository, IClientRepository clientRepository, IDropDownService dropDownService, IProductRepository productRepository, IPurchaseOrderRepository purchaseOrderRepository, IUserRepository userRepository, IAuditTrailRepository auditTrailRepository)
        {
            _pointOfPurchaseRepository = pointOfPurchaseRepository;
            _clientRepository = clientRepository;
            _dropDownService = dropDownService;
            _productRepository = productRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _userRepository = userRepository;
            _auditTrailRepository = auditTrailRepository;
        }

        public ActionResult Index()
        {
            ViewBag.msg = "";
            FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
            if (identity != null)
            {
                //var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                if (identity.Area == 0)
                {
                    ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";


                }
                else
                {
                    var pop = new List<PointOfPurchase>();//_pointOfPurchaseRepository.GetByArea(fsrDetails.AreaId);
                    return View(pop);
                }
            }
            else
            {
                ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";
            }
            return View();
        }
        [HttpPost]
        public ActionResult Index(string search)
        {

            ViewBag.msg = "";
            FsrCustomIdentity identity = (FsrCustomIdentity) User.Identity;
            if (identity != null)
            {
               // var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                if (identity.Area == 0)
                {
                    ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";


                }
                else
                {
                    var pop = _pointOfPurchaseRepository.GetBySearch(identity.Area, search);
                    return View(pop);
                }
            }
            {
                ViewBag.msg = "Contact your Field Sale Rep Administrator to assign you an area";
            }
            return View();
        }
        public ActionResult Order(int popId)
        {
            bind();
            OrderModel ord = new OrderModel();
            FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
            if (identity != null)
            {
                //var fsrDetails = (FsrUserDetail) Session[SessionConstant.FsrUserDetail];
                var client = _clientRepository.GetById(identity.Client);
                var pop = _pointOfPurchaseRepository.GetById(popId);
                var products = _productRepository.GetByClient(client.Id);
                ord.Id = Guid.NewGuid();
                ord.ClientName = client.Name;
                ord.ClientId = client.Id;
                ord.POPId = pop.Id;
                ord.POPName =pop.Name;
                OrderItemModel[] items = new OrderItemModel[products.Count];
                int i = 0;
                foreach (var p in products)
                {
                    OrderItemModel item = new OrderItemModel();
                    
                    item.ProductId = p.Id;
                    item.ProductName = p.Name;
                    item.Quantity = 0;
                    item.ReasonId = 0;
                    item.Id = i;
                    items[i]=item;
                    i++;
                }
                ord.Items = items;
                
            }
            return View(ord);
        }

        private void bind()
        {
            ViewBag.ReasonList = _dropDownService.GetReason();
        }

        [HttpPost]
        public ActionResult Order(OrderModel ord)
        {
            bind();
            if (ModelState.IsValid)
            {
                PurchaseOrder order = new PurchaseOrder();
                FsrCustomIdentity identity = (FsrCustomIdentity)User.Identity;
                if (ord != null && identity != null)
                {
                    //var fsrDetails = (FsrUserDetail)Session[SessionConstant.FsrUserDetail];
                    order.PopId = ord.POPId;
                    order.PurchaseOrderRef = "Ord" + DateTime.Now.ToString("yyyyMMddhhmmss");
                    order.ClientId = ord.ClientId;
                    order.FsrtId = identity.UserID;
                    order.Id = Guid.NewGuid();
                    foreach (var i in ord.Items)
                    {
                        PurchaseOrderItem item = new PurchaseOrderItem();
                        item.Price = 0;
                        item.Id = Guid.NewGuid();
                        item.Quantity = i.Quantity;
                        item.ReasonId = i.ReasonId != null ? i.ReasonId.Value:0;
                        item.ProductId = i.ProductId;
                        order.Items.Add(item);
                    }
                    _purchaseOrderRepository.Save(order);
                    Saveaudit("Added Order", HttpContext.User.Identity.Name, ActionType.Added);
                    return RedirectToAction("Next");
                }
            }else
            {
                ValidationSummary.DisplayValidationResult("Make sure you have entered all required details", ModelState);
            }
            return View(ord);
        }
         public ActionResult Next()
         {
             return View(); 
         }
         public void Saveaudit(string description, string username, ActionType actionType)
         {
             //  private IUserRepository _userRepository;
             //private IAuditTrailRepository _auditTrailRepository;
             // Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
             try
             {
                 User user = _userRepository.GetByUsername(username);
                 AuditTrail auditTrail = new AuditTrail();
                 auditTrail.Description = description;
                 auditTrail.UserId = user.Id;
                 auditTrail.ActionTypeId = Convert.ToInt32(actionType);
                 _auditTrailRepository.Save(auditTrail);
             }
             catch (Exception)
             {
                 throw;
             }
         }
    }
}
